package com.web;

import com.bean.User;
import com.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 返回包含 form 表单的页面
        req.getRequestDispatcher("/regist.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 进行数据库的插入，然后返回成功页面
        String username = req.getParameter("user_username");
        String password = req.getParameter("user_password");
        String gender = req.getParameter("user_gender");
        String email = req.getParameter("user_email");

        try {
            // 创建对象
            User user = new User();
            user.setUsername(username);
            user.setPassword(password);
            user.setGender(gender);
            user.setEmail(email);

            // 实现方法
            new UserDao().regist(user);

            // 把成功的信息保存到 message 中
            req.setAttribute("message", "注册成功");
            // 页面跳转
            req.getRequestDispatcher("/registResult.jsp").forward(req, resp);
        } catch (Exception e) {
            // 错误的信息打印到控制台
            e.printStackTrace();
            // 把失败的信息保存到 message 中
            req.setAttribute("message", "注册失败！" + e.getLocalizedMessage());
            // 页面跳转
            req.getRequestDispatcher("/registResult.jsp").forward(req, resp);
        }
    }
}
